package com.louzhu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.louzhu.common.utils.R;
import com.louzhu.gulimall.cart.feign.ProductFeignService;
import com.louzhu.gulimall.cart.interceptor.CartInterceptor;
import com.louzhu.gulimall.cart.service.CartService;
import com.louzhu.gulimall.cart.to.UserInfoTo;
import com.louzhu.gulimall.cart.vo.CartItemVo;
import com.louzhu.gulimall.cart.vo.CartVo;
import com.louzhu.gulimall.cart.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    // 统一购物车信息存储在redis的key前缀
    private final String CART_PREFIX = "gulimall:cart";

    /**
     * 加入购物车
     * @param skuId
     * @param num
     * @return
     */
    @Override
    public CartItemVo addToCart(Long skuId, int num) throws ExecutionException, InterruptedException {
        /*
        获取到要操作的购物车
         */
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        /*
        判断购物车中是否有次商品数据
         */
        String data = (String) cartOps.get(skuId.toString());

        if(StringUtils.isEmpty(data)){
            CartItemVo  cartItemVo = new CartItemVo();
        /*
        异步任务1 获取商品信息
         */
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 远程查询当前要添加的商品信息
                R skuInfoData = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = skuInfoData.getData(new TypeReference<SkuInfoVo>() {});
                // 商品信息添加到购物车
                cartItemVo.setCheck(true);
                cartItemVo.setCount(num);
                cartItemVo.setImage(skuInfo.getSkuDefaultImg());
                cartItemVo.setTitle(skuInfo.getSkuTitle());
                cartItemVo.setSkuId(skuId);
                cartItemVo.setPrice(skuInfo.getPrice());
            }, executor);

        /*
        异步任务2 远程查询Sku 属性组合信息
         */
            CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
                List<String> stingList = productFeignService.getStingList(skuId);
                cartItemVo.setSkuAttr(stingList);
            }, executor);

            /*
            等待异步任务完成
            将商品信息保存到指定的购物车 转为JSON格式存储
            返回封装好的购物车数据
             */
            CompletableFuture.allOf(getSkuInfoTask,getSkuAttrTask).get();
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            return cartItemVo;
        }else {
            // 从redis中获取当前购物车下的该商品数据
            CartItemVo cartItemVo = JSON.parseObject(data, CartItemVo.class);
            // 数量更新
            cartItemVo.setCount(cartItemVo.getCount() + num);
            // 更新redis
            String s = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(),s);
            // 返回购物车的商品数据
            return cartItemVo;
        }
    }

    /**
     * 获取某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {

        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String redisValue = (String) cartOps.get(skuId.toString());

        return JSON.parseObject(redisValue, CartItemVo.class);

    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     *
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时购物车的键
            String temptCartKey = CART_PREFIX + userInfoTo.getUserKey();

            //2、如果临时购物车的数据还未进行合并
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey);
            if (tempCartItems != null) {
                //临时购物车有数据需要进行合并操作
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清除临时购物车的数据
                clearCartInfo(temptCartKey);
            }

            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        } else {
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车里面的所有购物项
            List<CartItemVo> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }

        return cartVo;
    }

    /**
     * 选中购物车里的某一商品
     * @param skuId
     * @param checked
     */
    @Override
    public void checkItem(Long skuId, Integer checked) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        //修改商品状态
        cartItem.setCheck(checked == 1);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), redisValue);
    }

    /**
     * 修改购物项数量
     *
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {

        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), redisValue);
    }


    /**
     * 删除购物项
     *
     * @param skuId
     */
    @Override
    public void deleteIdCartInfo(Integer skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 清空临时购物车
     * @param temptCartKey
     */
    private void clearCartInfo(String temptCartKey) {
        redisTemplate.delete(temptCartKey);
    }

    /**
     * 获取购物车里面的数据
     *
     * @param temptCartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String temptCartKey) {
        //获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(temptCartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            return values.stream().map((obj) -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItemVo.class);
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 操作 redis 中 购物车数据 key: cartKey
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
    /*
    1、生成购物车数据在redis存储的key值
     */
        // 获取线程共享数据：用户信息
        UserInfoTo userInfoTo = CartInterceptor.toThreadLocal.get();
        // 购物车信息存储在redis中的key
        String cartKey = "";
        // 判断用户是否已登录，还是属于临时用户
        if(null != userInfoTo.getUserId()){
            // 用户已登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            // 属于临时用户
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        /*
        2、判断当前redis中是否已存在当前购物车数据，存在则修改，不存在则新增
         */
        // 绑定 redis 对 cartKey 的hash操作
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        return hashOps;
    }


}
